<?php
/**
 * FastApp.
 * 9/22/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Fastapp\Api\Service\Account;

use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Model\AccountMessage;
use Carbon\Carbon;

class MessageService extends BaseService
{
    public function list(array $param): array
    {
        $map['user_id'] = get_uid();
        if (isset($param['object_type']) && is_numeric($param['object_type'])) $map['object_type'] = $param['object_type'];
        $query = AccountMessage::query()->with(['log']);
        if (!empty($param['start_at'])) {
            $btw = [$param['start_at'] . ' 00:00:00', Carbon::createFromFormat('Y-m-d', $param['end_at'])->addDay()->toDateString() . ' 00:00:00'];
            $query->whereBetween('created_at', $btw);
        }
        $paginate = $query->where($map)->select(['id', 'title', 'content', 'object_type', 'object_id', 'status', 'created_at'])->where($map)->orderByDesc('id')->simplePaginate();
        AccountMessage::query()->where($map)->update(['status' => 1]);
        return ['list' => $paginate->items()];
    }

    public function last(): array
    {
        return [
            'unread_num' => AccountMessage::query()->where(['user_id' => get_uid(), 'status' => 0])->count()
        ];
    }

    public static function add(array $data): array
    {
        return AccountMessage::query()->create($data)->toArray();
    }
}